package logic

import (
	"context"
	"encoding/json"
	"errors"

	"bigmodel/internal/svc"
	"bigmodel/internal/types"
	"bigmodel/model"
	"bigmodel/service/chat/aliyun"
	"bigmodel/service/chat/spark"
	"bigmodel/service/common"

	"github.com/zeromicro/go-zero/core/logx"
)

type EditConfigLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	pfmodel model.PlatformModel
}

func NewEditConfigLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EditConfigLogic {
	return &EditConfigLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		pfmodel: model.NewPlatformModel(svcCtx.Orm),
	}
}

func (l *EditConfigLogic) EditConfig(req *types.EditConfigRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	// 身份校验

	// 修改值
	pt,err := l.pfmodel.FindOne(l.ctx,common.DecodeIdString(req.Id,""))
	if err != nil {
		return nil,errors.New("查询失败")
	}
	var conf string
	switch pt.Name{
	case "spark":
		param := &spark.RequestParameterChat{}
		err := json.Unmarshal([]byte(pt.InputConf),param)
		if err != nil {
			return nil,errors.New("json序列化错误")
		}
		if req.MaxTokens != 0 {
			param.MaxTokens = int(req.MaxTokens)
		}
		if req.Temperature !=  0.0{
			param.Temperature = req.Temperature
		}
		bt,err := json.Marshal(param)
		if err != nil {
			return nil,errors.New("反序列化失败")
		}
		conf = string(bt)
		break
	case "aliyun":
		param := &aliyun.Parameters{}
		err := json.Unmarshal([]byte(pt.InputConf),param)
		if err != nil {
			return nil,errors.New("json序列化错误")
		}
		if req.MaxTokens != 0 {
			param.MaxTokens = req.MaxTokens
		}
		if req.Temperature !=  0.0{
			param.Temperature = float32(req.Temperature)
		}
		bt,err := json.Marshal(param)
		if err != nil {
			return nil,errors.New("反序列化失败")
		}
		conf = string(bt)
		break
	}
	pt.InputConf = conf
	err = l.pfmodel.Update(l.ctx,pt)
	if err != nil {
		return nil,errors.New("更新失败")
	}
	return &types.CommonResponse{
		Code: 200,
		Msg: "更新成功",
	},nil
}
